<template>
  <div>
    <div v-if="isPointer">
      <el-form :inline="true">
        <el-form-item label="X1">
          <el-input v-model="pointerData[0].markLine.data[0].xAxis" @change="inputDragging([0], [pointerData[0].markLine.data[0].xAxis])"/>
        </el-form-item>
        <el-form-item label="X2">
          <el-input v-model="pointerData[1].markLine.data[0].xAxis" @change="inputDragging([1], [pointerData[1].markLine.data[0].xAxis])"/>
        </el-form-item>
      </el-form>
    </div>
    <div
      :id="containerId"
      :style="{'width': '100%', 'min-width': _width ? _width : '400px', 'height': _height ? _height : '400px'}"
      class="chartContainer}"
      oncontextmenu="return false" />
  </div>
</template>
<script>
// import Echarts from 'echarts'
import themeEcharts from "../assets/css/themeEcharts";
const Echarts = require("echarts");
var UUID = require("uuid");
// import UUID from 'uuid'
export default {
  props: {
    title: {
      type: Object,
      default: function() {
        return {};
      }
    },
    legend: {
      type: Object,
      default: function() {
        return {};
      }
    },
    dataset: {
      type: Object,
      default: function() {
        return {};
      }
    },
    grid: {
      type: Array,
      default: function() {
        return [];
      }
    },
    axisPointer: {
      type: Object,
      default: function() {
        return {};
      }
    },
    xAxis: {
      type: Array,
      default: function() {
        return [];
      }
    },
    yAxis: {
      type: Array,
      default: function() {
        return [];
      }
    },
    polar: {
      type: Object,
      default: function() {
        return {};
      }
    },
    radiusAxis: {
      type: Object,
      default: function() {
        return {};
      }
    },
    angleAxis: {
      type: Object,
      default: function() {
        return {};
      }
    },
    radar: {
      type: Object,
      default: function() {
        return {};
      }
    },
    dataZoom: {
      type: Array,
      default: function() {
        return [];
      }
    },
    visualMap: {
      type: Object,
      default: function() {
        return {};
      }
    },
    tooltip: {
      type: Object,
      default: function() {
        return {};
      }
    },
    toolbox: {
      type: Object,
      default: function() {
        return {};
      }
    },
    brush: {
      type: Object,
      default: function() {
        return {};
      }
    },
    geo: {
      type: Object,
      default: function() {
        return {};
      }
    },
    parallel: {
      type: Object,
      default: function() {
        return {};
      }
    },
    parallelAxis: {
      type: Object,
      default: function() {
        return {};
      }
    },
    singleAxis: {
      type: Object,
      default: function() {
        return {};
      }
    },
    timeline: {
      type: Object,
      default: function() {
        return {};
      }
    },
    series: {
      type: Array,
      default: function() {
        return [];
      }
    },
    color: {
      type: Array,
      default: function() {
        return [];
      }
    },
    backgroundColor: {
      type: String,
      default: ""
    },
    group: {
      type: String,
      default: ""
    },
    data: {
      type: [Array, Object],
      default: function() {
        return [];
      }
    },
    graphic: {
      type: Array,
      default: function() {
        return [];
      }
    },
    _width: {
      type: String,
      default: ""
    },
    _height: {
      type: String,
      default: ""
    },
    isPointer: {
      type: Boolean,
      default: false
    },
    isLink: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      echart: {},
      containerId: UUID.v4(),
      symbolSize: [20, 300],
      pointerData: [
        {
          id: 0,
          type: "scatter",
          markLine: {
            data: [{ xAxis: 0 }]
          }
        },
        {
          id: 1,
          type: "scatter",
          markLine: {
            data: [{ xAxis: 0 }]
          }
        },
        {
          id: "pointer",
          type: "scatter",
          smooth: true,
          symbolSize: [10, 100],
          data: []
        }
      ]
    };
  },
  // 监听数据是否发生变化
  watch: {
    title: {
      handler(title) {
        this.$nextTick(() => {
          this.echart.setOption({
            title
          });
        });
      },
      deep: true
    },
    grid: {
      handler(grid) {
        this.$nextTick(() => {
          this.echart.setOption({
            grid
          });
        });
      },
      deep: true
    },
    axisPointer: {
      handler(grid) {
        this.$nextTick(() => {
          this.echart.setOption({
            grid
          });
        });
      },
      deep: true
    },
    xAxis: {
      handler(xAxis) {
        this.$nextTick(() => {
          this.echart.setOption({
            xAxis
          });
        });
      },
      deep: true
    },
    dataset: {
      handler(dataset) {
        this.$nextTick(() => {
          this.echart.setOption({
            dataset
          });
        });
      },
      deep: true
    },
    yAxis: {
      handler(yAxis) {
        this.$nextTick(() => {
          this.echart.setOption({
            yAxis
          });
        });
      },
      deep: true
    },
    polar: {
      handler(polar) {
        this.$nextTick(() => {
          this.echart.setOption({
            polar
          });
        });
      },
      deep: true
    },
    radiusAxis: {
      handler(radiusAxis) {
        this.$nextTick(() => {
          this.echart.setOption({
            radiusAxis
          });
        });
      },
      deep: true
    },
    angleAxis: {
      handler(angleAxis) {
        this.$nextTick(() => {
          this.echart.setOption({
            angleAxis
          });
        });
      },
      deep: true
    },
    radar: {
      handler(radar) {
        this.$nextTick(() => {
          this.echart.setOption({
            radar
          });
        });
      },
      deep: true
    },
    dataZoom: {
      handler(dataZoom) {
        this.$nextTick(() => {
          this.echart.setOption({
            dataZoom
          });
        });
      },
      deep: true
    },
    visualMap: {
      handler(visualMap) {
        this.$nextTick(() => {
          this.echart.setOption({
            visualMap
          });
        });
      },
      deep: true
    },
    tooltip: {
      handler(tooltip) {
        console.log(tooltip);
        this.$nextTick(() => {
          this.echart.setOption({
            tooltip
          });
        });
      },
      deep: true
    },
    toolbox: {
      handler(toolbox) {
        this.$nextTick(() => {
          this.echart.setOption({
            toolbox
          });
        });
      },
      deep: true
    },
    brush: {
      handler(brush) {
        this.$nextTick(() => {
          this.echart.setOption({
            brush
          });
        });
      },
      deep: true
    },
    geo: {
      handler(geo) {
        this.$nextTick(() => {
          this.echart.setOption({
            geo
          });
        });
      },
      deep: true
    },
    parallel: {
      handler(parallel) {
        this.$nextTick(() => {
          this.echart.setOption({
            parallel
          });
        });
      },
      deep: true
    },
    parallelAxis: {
      handler(parallelAxis) {
        this.$nextTick(() => {
          this.echart.setOption({
            parallelAxis
          });
        });
      },
      deep: true
    },
    singleAxis: {
      handler(singleAxis) {
        this.$nextTick(() => {
          this.echart.setOption({
            singleAxis
          });
        });
      },
      deep: true
    },
    timeline: {
      handler(timeline) {
        this.$nextTick(() => {
          this.echart.setOption({
            timeline
          });
        });
      },
      deep: true
    },
    series: {
      handler(series) {
        this.$nextTick(() => {
          this.echart.setOption({
            legend: this.legend,
            series
          });
        });
      },
      deep: true
    },
    color: {
      handler(color) {
        this.$nextTick(() => {
          this.echart.setOption({
            color
          });
        });
      }
    },
    backgroundColor: {
      handler(backgroundColor) {
        this.$nextTick(() => {
          this.echart.setOption({
            backgroundColor
          });
        });
      }
    },
    group: {
      handler(group) {
        this.handlerConnect(group);
      }
    },
    graphic: {
      handler(graphic) {
        this.$nextTick(() => {
          this.echart.setOption({
            graphic
          });
        });
      },
      deep: true
    },
    _height: {
      handler(_height) {
        console.log("handler里面的height", _height);
        this.$nextTick(() => {
          this.echart.resize();
        });
      }
    },
    _width: {
      handler(_width) {
        this.$nextTick(() => {
          this.echart.resize();
        });
      }
    },
    data: {
      handler(data) {
        if (!data) return;
        var series = [];
        data.map((obj, idx) => {
          series.push({
            data: obj
          });
        });
        this.$nextTick(() => {
          this.echart.setOption({
            series
          });
        });
      }
    },
    isPointer: {
      handler(isPointer) {}
    },
    pointerData: {
      handler(data) {
        if (this.isLink) {
          this.$emit("linkHandle", data);
        }
      },
      deep: true
    }
  },
  beforeDestroy() {
    if (this.echart) {
      Echarts.dispose(this.echart);
    }
  },
  // 组件创建完成时
  mounted() {
    const vm = this;
    this.$nextTick(() => {
      this.echart = Echarts.init(
        document.getElementById(this.containerId),
        themeEcharts
      );

      if (this.group) this.handlerConnect(this.group);

      this.echart.setOption(this.getDefaultOption());

      this.echart.on("click", function(params) {
        vm.$emit("chart-click-data", {
          data: params,
          id: vm.$el.id,
          echart: vm.echart
        });
      });
      this.echart.on("brushEnd", params => {
        console.log(params, "brush");
        vm.$emit("chart-brush-data", {
          data: params,
          id: vm.$el.id,
          echart: vm.echart
        });
      });
      this.echart.on("dataZoom", params => {
        console.log(params, "brush");
        vm.$emit("chart-zoom-data", {
          data: params,
          id: vm.$el.id,
          echart: vm.echart
        });
      });
      if (this.isPointer) {
        if (this.series[0].data.length === 0) {
          return false;
        }
        var myChart = this.echart;
        var data1 = this.series[0].data[0];
        var data2 = this.series[0].data[this.series[0].data.length - 1];
        this.pointerData[0].markLine.data = [{ xAxis: data1[0] }];
        this.pointerData[1].markLine.data = [{ xAxis: data2[0] }];
        this.pointerData[2].data = [[data1[0], data1[1]], [data2[0], data2[1]]];
        myChart.setOption({
          series: [this.pointerData[0], this.pointerData[1]]
        });
        this.handlePointer();
      }
    });
  },
  methods: {
    changeStyle(data) {
      console.log(data, "changeStyle");
      this.$nextTick(() => {
        this.echart.dispatchAction({
          type: "downplay"
          // seriesIndex: 0,//这行不能省
          // dataIndex: data.dataIndex
        });
        this.echart.dispatchAction({
          type: "highlight",
          seriesIndex: data.seriesIndex, // 这行不能省
          dataIndex: data.dataIndex
        });
      });
    },
    brushSelect(data) {
      this.$nextTick(() => {
        this.echart.dispatchAction({
          type: "brush",
          areas: [
            {
              brushType: "lineX",
              coordRange: data,
              xAxisIndex: 0
            }
          ]
        });
      });
    },
    zoomSelect(data) {
      this.$nextTick(() => {
        this.echart.dispatchAction({
          type: "dataZoom",
          startValue: data.startValue,
          endValue: data.endValue
        });
      });
      /* this.echart.dispatchAction({
        type: 'dataZoom',
        start: 20,
        end: 30
      })*/
    },
    handlerConnect(group) {
      if (group) {
        Echarts.connect(group);
      }
      this.echart.group = group;
    },
    getDefaultOption() {
      /* var option = {
        title: this.title,
        legend: this.legend,
        tooltip: this.tooltip,
        toolbox: this.toolbox,
        brush: this.brush,
        grid: this.grid,
        xAxis: this.xAxis,
        yAxis: this.yAxis,
        /!* yAxis: [
          {
            type: 'value',
            axisLine: {
              lineStyle: {
                color: '#fff'
              }
            }
          }
        ],*!/
        useUTC: false,
        dataZoom: this.dataZoom,
        series: this.series,
        graphic: this.graphic
      }
      if (JSON.stringify(this.toolbox) === '{}') {
        option.toolbox = {
          show: false
        }
      }*/
      var otherEcharts = {};
      if (JSON.stringify(this.visualMap) !== "{}") {
        otherEcharts["visualMap"] = this.visualMap;
      }
      if (JSON.stringify(this.axisPointer) !== "{}") {
        otherEcharts["axisPointer"] = this.axisPointer;
      }
      if (JSON.stringify(this.dataset) !== "{}") {
        otherEcharts["dataset"] = this.dataset;
      }
      if (JSON.stringify(this.xAxis) !== "{}") {
        otherEcharts["xAxis"] = this.xAxis;
        otherEcharts["yAxis"] = this.yAxis;
      }
      if (JSON.stringify(this.brush) !== "{}") {
        otherEcharts["brush"] = this.brush;
      }
      /* if (JSON.stringify(this.tooltip) === '{}') {
        this.tooltip = {
          trigger: 'axis'
        }
      }*/

      /* 判断是否是热力图或者是带有可以拖动时间的功能*/
      var option = {
        title: this.title,
        legend: this.legend,
        tooltip: this.tooltip,
        toolbox: this.toolbox,
        grid: this.grid,
        useUTC: false,
        dataZoom: this.dataZoom,
        series: this.series,
        graphic: this.graphic
      };

      option = Object.assign(option, otherEcharts);

      return option;
    },
    sizeChange() {
      this.$nextTick(() => {
        this.echart.resize();
      });
    },
    clearEchart() {
      var vm = this;
      vm.echart = Echarts.init(
        document.getElementById(vm.containerId),
        themeEcharts
      );
      if (vm.group) vm.handlerConnect(vm.group);
      var series = vm.getDefaultOption().series;
      var seriesLength = series.length;
      for (var i = 0; i < seriesLength; i++) {
        series.shift();
      }
      vm.echart.setOption(vm.getDefaultOption());
      vm.echart.on("click", function(params) {
        vm.$emit("chart-click-data", {
          data: params,
          id: vm.$el.id,
          echart: vm.echart
        });
      });
    },
    handlePointer() {
      console.log(this.pointerData[2].data, "this.pointerData");
      var myChart = this.echart;
      const symbolSize = this.symbolSize;
      var data = this.pointerData[2].data;
      const that = this;
      setTimeout(() => {
        // Add shadow circles (which is not visible) to enable drag.
        myChart.setOption({
          graphic: data.map(function(item, dataIndex) {
            return {
              type: "circle",
              position: myChart.convertToPixel("grid", item),
              shape: {
                cx: 0,
                cy: 0,
                r: symbolSize[1] / 2
              },
              invisible: true,
              draggable: true,
              ondrag: function(dx, dy) {
                that.onPointDragging(dataIndex, [this.x, this.y]);
              },
              onmousemove: function() {
                that.showTooltip(dataIndex);
              },
              onmouseout: function() {
                that.hideTooltip(dataIndex);
              },
              z: 100
            };
          })
        });
      }, 0);
    },
    showTooltip(dataIndex) {
      var myChart = this.echart;
      myChart.dispatchAction({
        type: "showTip",
        seriesIndex: 0,
        dataIndex: dataIndex
      });
    },
    hideTooltip(dataIndex) {
      var myChart = this.echart;
      myChart.dispatchAction({
        type: "hideTip"
      });
    },
    onPointDragging(dataIndex, pos) {
      var myChart = this.echart;
      var data = myChart.convertFromPixel("grid", pos)[0];
      this.pointerData[2].data[dataIndex][0] = data;
      this.pointerData[dataIndex].markLine.data[0].xAxis = data;
      // Update data
      myChart.setOption({
        series: [
          {
            id: dataIndex,
            type: "scatter",
            markLine: {
              data: [{ xAxis: data }]
            }
          }
        ]
      });
    },
    inputDragging(dataIndex, val) {
      var series = [];
      dataIndex.map((item, index) => {
        this.pointerData[2].data[item][0] = Number(val[index]);
        this.pointerData[item].markLine.data[0].xAxis = Number(val[index]);
        series.push({
          id: item,
          type: "scatter",
          markLine: {
            data: [{ xAxis: Number(val[index]) }]
          }
        });
      });
      const symbolSize = this.symbolSize;
      var myChart = this.echart;
      var data = this.pointerData[2].data;
      myChart.setOption({
        series: series,
        graphic: data.map(function(item, dataIndex) {
          return {
            type: "circle",
            position: myChart.convertToPixel("grid", item),
            shape: {
              cx: 0,
              cy: 0,
              r: symbolSize[1] / 2
            },
            invisible: true,
            draggable: true,
            z: 100
          };
        })
      });
    }
  }
};
</script>
